package My

import (
	"errors"
	"fmt"
	"db2s/ETL"
	"db2s/global"
	"strconv"
)

type TableSum struct{}

/*
Rows MySQL 查询表的统计信息中行数
*/
func (my TableSum) Rows(s global.TableSumInput) (rowsCount global.RowsReturnResult, err error) {
	var (
		event = "[MySQLRows]"
		f1    any
	)
	rowsCount.BaseResult.Sql = fmt.Sprintf("select TABLE_ROWS as tableRows from information_schema.tables where table_schema='%v' and table_name ='%v'", s.TableInfo.Schema, s.TableInfo.BackendTableName)
	//收集统计信息
	if rowsCount.BaseResult.TimeOut, f1, err = ExecSelectSql(ExecSqlInputS{
		Ss:           s,
		Event:        event,
		SelectSqlStr: rowsCount.BaseResult.Sql,
		Expect:       ETL.Map,
	}); err != nil || f1 == nil {
		if err != nil {
			err = errors.New(fmt.Sprintf("%v %v", event, err))
		}
		return
	}
	if rowsCount.Result, err = strconv.ParseUint(fmt.Sprintf("%v", f1.(map[string]any)["tableRows"]), 10, 64); err != nil {
		err = errors.New(fmt.Sprintf("%v table sum conversion int failed. process:{sql:%v,shard:%v,db:%v,result:%v,err:%v}", event, rowsCount.BaseResult.Sql, "single", s.Db, f1, err))
		return
	}
	if s.TableInfo.RowsLimit > 0 {
		rowsCount.Result = uint64(s.TableInfo.RowsLimit)
	}
	return
}
func (my TableSum) Count(s global.TableSumInput) (rowsCount global.CountReturnResult, err error) {
	var (
		event = "[MySQLCount]"
		f1    any
	)
	rowsCount.BaseResult.Sql = fmt.Sprintf("select \n"+
		"/*+ SET_VAR(innodb_parallel_read_threads=5) */ count(1) as `tableRows` \n"+
		"from %v where 1=1 \n"+
		"%v %v %v",
		tableObject(s.TableInfo.Schema, s.TableInfo.BackendTableName, s.TableInfo.PartitionName),
		whereSqlFilter(s.SqlFilter.WhereSql),
		whereSqlFilter(s.SqlFilter.WhereAdd),
		rowsLimitC(s.TableInfo.RowsLimit))
	if rowsCount.BaseResult.TimeOut, f1, err = ExecSelectSql(ExecSqlInputS{
		Ss:           s,
		Event:        event,
		SelectSqlStr: rowsCount.BaseResult.Sql,
		Expect:       ETL.Map,
	}); err != nil || f1 == nil {
		if err != nil {
			err = errors.New(fmt.Sprintf("%v %v", event, err))
		}
		return
	}
	if rowsCount.Result, err = strconv.ParseUint(fmt.Sprintf("%v", f1.(map[string]any)["tableRows"]), 10, 64); err != nil {
		err = errors.New(fmt.Sprintf("%v table sum conversion int failed. process:{sql:%v,shard:%v,db:%v,result:%v,err:%v}", event, rowsCount.BaseResult.Sql, s.TableInfo.ShardName, s.Db, f1, err))
		return
	}
	return
}
func (my TableSum) CountDirect(s global.TableSumInput) (bool, int64) {
	switch {
	case len(s.IndexColumn) == 0:
		return true, int64(len(s.PartitionNameGarth))
	default:
		return false, int64(len(s.PartitionNameGarth))
	}
}
